<style lang="less">
  .ue-organization {
    .el-select, .el-cascader {
      width: 100%
    }
    .fa-search, .fa-hand-pointer-o {
      color: #20a0ff;
      padding-right: 7px;
    }
    .column {
      display: flex;
      flex-direction: column;
      .el-table {
        overflow-y: auto;
        flex: 1;
      }
      .el-tabs {
        margin-top: 38px;
        flex: 1;
        display: flex;
        flex-direction: column;
        .el-tabs__content {
          flex: 1;
          display: flex;
          .el-tab-pane {
            flex: 1;
            display: flex;
            flex-direction: column;
          }
        }
      }
    }
  }

</style>

<template>
  <div class="columns ue-organization">
    <div class="column">
      <el-col :span="24" style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-col>
      <ue-el-tree-table
        height="100%"
        tree-structure
        tree-expand-all
        highlight-current-row
        border
        v-loading="listLoading"
        @current-change="handleCurrentChange"
        :data-source="organizationTree">
        <el-table-column prop="typeName" label="类型" width="70">
        </el-table-column>
        <el-table-column prop="attributeName" label="属性" width="70">
        </el-table-column>
        <el-table-column prop="divideRatio" label="零担分成" width="100">
        </el-table-column>
        <!--<el-table-column prop="truckLoadDivideRatio" label="整车分成" width="100">-->
        <!--</el-table-column>-->
        <el-table-column prop="sort" label="序号" width="70">
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </ue-el-tree-table>
    </div>
    <div class="column">
      <el-tabs type="border-card">
        <el-tab-pane label="资源分配管理">
          <organization-resource ref="organizationResource"></organization-resource>
        </el-tab-pane>
        <el-tab-pane label="用户分配管理">
          <el-col :span="24" style="margin-bottom: 10px">
            <el-button type="primary" @click="addUser" :disabled="this.selectedRow==null">分配</el-button>
            <el-button type="primary" @click="removeCurrentOrgUser" :disabled="this.currentOrgUserSels.length===0">移除
            </el-button>
          </el-col>
          <el-table highlight-current-row border
                    :data="currentOrgUserData"
                    @selection-change="haveCurrentOrgUserSelsChange"
                    style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="userName" label="用户名">
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="130">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="130">
            </el-table-column>
            <el-table-column label="操作" width="330">
              <template slot-scope="scope">
                <el-button  @click="handleRole(scope.$index, scope.row)">角色分配</el-button>
                <el-button  @click="handleDataPermission(scope.$index, scope.row)">数据组分配</el-button>
                <el-button :disabled="scope.row.defaultOrganizationId === selectedRow.id"
                           @click="handleDefaultOrgainzaion(scope.$index, scope.row)">设为默认组织
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="辐射范围管理">
          <el-col :span="24" style="margin-bottom: 10px">
            <el-button type="primary" @click="addRadiateScope">新增</el-button>
          </el-col>
          <el-table highlight-current-row border :data="radiateScopeTableData" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!--<el-table-column prop="typeName" label="类型">-->
            <!--</el-table-column>-->
            <el-table-column prop="startProvinceName" label="起点省">
            </el-table-column>
            <el-table-column prop="startCityName" label="起点市">
            </el-table-column>
            <el-table-column prop="startCountyName" label="起点区">
            </el-table-column>
            <el-table-column prop="endProvinceName" label="终点省">
            </el-table-column>
            <el-table-column prop="endCityName" label="终点市">
            </el-table-column>
            <el-table-column prop="endCountyName" label="终点区">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button  style="margin-bottom: 10px" @click="modifyRadiateScope(scope.row)">编辑
                </el-button>
                <el-button size="danger" style="margin-left: 0" @click="deleteRadiateScope(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-col class="f-mt10" :span="24">
            <el-pagination
              :current-page="cPage"
              :page-size="pSize"
              @size-change="hChange"
              @current-change="hCChange"
              layout="total,sizes,prev,pager,next,jumper"
              :total="tts" style="float: right">
            </el-pagination>
          </el-col>

        </el-tab-pane>
        <el-tab-pane label="网点规则">
          <dot-rule ref="dotRule"></dot-rule>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog title="角色分配" size="tiny" :visible.sync="roleWinVisible" :close-on-click-modal="false">
      <el-select v-model="currentUserCurrentOrgRoleIds" multiple placeholder="请选择角色">
        <el-option
          v-for="item in currentOrgRoles"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addCurrentUserRoles">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="数据组分配" size="tiny" :visible.sync="dataPermissionWinVisible" :close-on-click-modal="false">
      <el-select v-model="currentUserCurrentOrgDataPermissionIds" multiple placeholder="请选择数据组">
        <el-option
          v-for="item in currentOrgDataPermissions"
          :key="item.id"
          :label="item.dataPermissionName"
          :value="item.id">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dataPermissionWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addCurrentUserDataPermissions">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户列表" size="tiny" :visible.sync="noCurrentOrgUserWinVisible" :close-on-click-modal="false">
      <el-col :span="24" style="margin-bottom: 10px">
        <el-button type="primary" @click="addCurrentOrgUser" :disabled="this.noCurrentOrgUserSels.length===0">保存
        </el-button>
      </el-col>
      <el-table ref="noCurrentOrgUserDataTable" highlight-current-row border
                :data="noCurrentOrgUserData"
                @selection-change="haveNoCurrentOrgUserSelsChange"
                height="400"
                style="width: 100%;">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="userName" label="用户名">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="130">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :title="dialogTitle" size="tiny" :visible.sync="myFormVisible" :close-on-click-modal="false">
      <el-form :model="myForm" label-width="80px" ref="myForm">
        <el-form-item label="组织ID">
          <el-input v-model="myForm.id" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="组织名称"
                      :rules="[{ required: true, message: '请输入组织名称', trigger: 'blur' },
                                     { max: 30, message: '长度不能超过 30 个字符', trigger: 'blur' }]"
                      prop="name">
          <el-input v-model="myForm.name"></el-input>
        </el-form-item>
        <el-form-item label="类型"
                      :rules="[{type:'integer',required: true, message: '请选择类型', trigger: 'change' }]"
                      prop="type">
          <el-select v-model="myForm.type" placeholder="请选择类型">
            <el-option
              v-for="item in $store.getters.ORGANIZATION_TYPE"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性"
                      :rules="[{type:'integer',required: true, message: '请选择属性', trigger: 'change' }]"
                      prop="attribute">
          <el-select v-model="myForm.attribute" placeholder="请选择类型">
            <el-option
              v-for="item in $store.getters.ORGANIZATION_ATTRIBUTE"
              :key="item.dictVal"
              :label="item.cnDictValname"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="别名"
                      prop="alias">
          <el-input v-model="myForm.alias"></el-input>
        </el-form-item>
        <el-form-item v-if="110007002 === myForm.attribute" v-for="(domain, index) in myForm.jurisdictions" :key="index"
                      label="管辖区域"
                      :rules="{required: true, type: 'array', message: '请选择管辖区域', trigger: 'change'}"
                      :prop="'jurisdictions.' + index + '.ids'">
          <el-cascader
            style="width: 200px;"
            v-model="domain.ids"
            placeholder="请选择"
            :options="$store.state.addressDicts"
            :props="{value: 'id',label: 'name'}">
          </el-cascader>
          <el-button type="primary" icon="el-icon-minus" v-if="index !== myForm.jurisdictions.length-1"
                     @click="removeJurisdictions(index)"></el-button>
          <el-button type="primary" icon="el-icon-plus" v-if="index === myForm.jurisdictions.length-1"
                     @click="addJurisdictions"></el-button>
        </el-form-item>
        <el-form-item v-if="myForm.attribute === 110007002 || myForm.attribute === 110007003" label="零担分成"
                      :rules="[{type:'number',required: true, message: '请输入分成比例', trigger: 'blur' }]"
                      prop="divideRatio">
          <el-input v-model.number="myForm.divideRatio" placeholder="请输入分成比例"></el-input>
        </el-form-item>
        <!--<el-form-item v-if="myForm.attribute === 110007002" label="整车分成"-->
                      <!--:rules="[{type:'number',required: true, message: '请输入分成比例', trigger: 'blur' }]"-->
                      <!--prop="truckLoadDivideRatio">-->
          <!--<el-input v-model.number="myForm.truckLoadDivideRatio" placeholder="请输入分成比例"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item style="margin-bottom:0px;" v-if="myForm.attribute === 110007003">
          <el-checkbox v-model.number="myForm.deduction">计算专线收益时扣除该分成比例</el-checkbox>
        </el-form-item>
        <el-form-item label="序号"
                      :rules="[{ type:'integer',required: true, message: '请输入整数', trigger: 'blur' }]"
                      prop="sort">
          <el-input v-model.number="myForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="父组织" prop="pid">
          <el-cascader
            clearable
            :options="organizationTree"
            change-on-select
            :props="props"
            v-model="pids">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="myFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="radiateScopeDialogTitle" size="tiny" :visible.sync="radiateScopeFormDialog">
      <el-form :model="radiateScopeForm" label-width="90px" ref="radiateScopeForm">
        <el-form-item label="起点省" prop="startProvinces" :rules="{validator: this.radiateScopeFormFun}">
          <el-cascader
            v-model="radiateScopeForm.startProvinces"
            placeholder="请选择省"
            :options="radiateScopeProvince"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="起点市" prop="startCitys" :rules="{validator: this.cityFun}">
          <el-cascader
            v-model="radiateScopeForm.startCitys"
            placeholder="请选择市"
            :options="radiateScopeCity"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="起点区" prop="startCountys" :rules="{validator: this.countyFun}">
          <el-cascader
            v-model="radiateScopeForm.startCountys"
            placeholder="请选择区"
            :options="radiateScopeCounty"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="终点省" prop="endProvinces">
          <el-cascader
            v-model="radiateScopeForm.endProvinces"
            placeholder="请选择省"
            :options="radiateScopeProvince"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="终点市" prop="endCitys" :rules="{validator: this.notCityFun}">
          <el-cascader
            v-model="radiateScopeForm.endCitys"
            placeholder="请选择市"
            :options="radiateScopeCity"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="终点区" prop="endCountys" :rules="{validator: this.notCountyFun}">
          <el-cascader
            v-model="radiateScopeForm.endCountys"
            placeholder="请选择区"
            :options="radiateScopeCounty"
            change-on-select
            :props="props"
          ></el-cascader>
        </el-form-item>
        <!--<el-form-item label="管辖类型" prop="type" :rules="{required: true, message: '请输入管辖类型', trigger: 'blur' }">-->
        <!--<el-radio class="radio" v-model="radiateScopeForm.type" label="10001">起点</el-radio>-->
        <!--<el-radio class="radio" v-model="radiateScopeForm.type" label="10002">终点</el-radio>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="radiateScopeFormDialog = false">取消</el-button>
        <el-button type="primary" @click="createRadiateScopeClick">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addressDicts } from '../../../api/system/addressDict.js';
import {
  organizationTree, deleteOrganization,
  saveOrganization, addUsers, removeUsers, addOrganizationRadiateScopes,
  getOrganizationRadiateScopes, deleteOrganizationRadiateScopes
} from '../../../api/organization/Organization';
import { searchAllUsers, addRoles, addDataPermissions, setCurrentOrgid } from '../../../api/organization/user';
import { isEmpty, getTreeIdAndNameToMap } from '../../../lib/util.js';
import DotRule from './DotRule.vue';
import OrganizationResource from './OrganizationResource.vue';

export default {
  components: {
    OrganizationResource,
    DotRule
  },
  data () {
    return {
      tts: 0,
      cPage: 1,
      pSize: 10,
      currentUserCurrentOrgRoleIds: [],
      currentUserNoCurrentOrgRoleIds: [],
      currentUserCurrentOrgDataPermissionIds: [],
      currentUserNoCurrentOrgDataPermissionIds: [],
      currentOrgRoles: [],
      currentOrgRoleIds: [],
      currentOrgDataPermissions: [],
      currentOrgDataPermissionIds: [],
      roleWinVisible: false,
      dataPermissionWinVisible: false,
      listLoading: false,
      organizationTree: [],
      resourceTree: [],
      props: {
        value: 'id',
        label: 'name'
      },
      selectedRow: null,
      pids: [],
      myForm: {
        id: null,
        name: null,
        type: null,
        sort: null,
        alias: null,
        attribute: null,
        divideRatio: null,
        truckLoadDivideRatio: null,
        deduction: null,
        jurisdictions: [{ids: []}],
        parent: {id: null}
      },
      dialogTitle: '',
      myFormVisible: false,
      currentOrgUserData: [],
      noCurrentOrgUserData: [],
      currentOrgUserSels: [],
      noCurrentOrgUserSels: [],
      noCurrentOrgUserWinVisible: false,
      radiateScopeFormDialog: false,
      radiateScopeDialogTitle: '新增',
      radiateScopeProvince: [],
      radiateScopeCity: [],
      radiateScopeCounty: [],
      radiateScopeTableData: [],
      radiateScopeForm: {
        startProvinces: [],
        startProvince: '',
        startProvinceName: '',
        startCitys: [],
        startCity: '',
        startCityName: '',
        startCountys: [],
        startCounty: '',
        startCountyName: '',
        endProvinces: [],
        endProvince: '',
        endProvinceName: '',
        endCitys: [],
        endCity: '',
        endCityName: '',
        endCountys: [],
        endCounty: '',
        endCountyName: '',
        organizationId: '',
        organizationName: ''
        //          type: '',
        //          typeName: ''
      }
    };
  },
  watch: {
    pids (val) {
      if (val.length > 0) {
        this.myForm.parent.id = val[val.length - 1];
      } else {
        this.myForm.parent.id = null;
      }
    },
    'myForm.attribute': {
      handler: function (val, oldVal) {
        if (val === 110007002 && this.myForm.jurisdictions.length === 0) {
          this.myForm.jurisdictions.push({ids: []});
        }
      },
      deep: true
    }
  },
  methods: {
    removeJurisdictions (index) {
      this.myForm.jurisdictions.splice(index, 1);
    },
    addJurisdictions () {
      this.myForm.jurisdictions.push({ids: []});
    },
    radiateScopeFormFun (rule, value, callback) {
      if (isEmpty(this.radiateScopeForm.startProvinces) && isEmpty(this.radiateScopeForm.startCitys) &&
          isEmpty(this.radiateScopeForm.startCountys) && isEmpty(this.radiateScopeForm.endProvinces) &&
          isEmpty(this.radiateScopeForm.endCitys) && isEmpty(this.radiateScopeForm.endCountys)) {
        return callback(new Error('至少选择一项才能保存'));
      }
      callback();
    },
    cityFun (rule, value, callback) {
      if (!isEmpty(this.radiateScopeForm.startCitys) && this.radiateScopeForm.startCitys.length < 2) {
        return callback(new Error('请选择到市'));
      }
      callback();
    },
    notCityFun (rule, value, callback) {
      if (!isEmpty(this.radiateScopeForm.endCitys) && this.radiateScopeForm.endCitys.length < 2) {
        return callback(new Error('请选择到市'));
      }
      callback();
    },
    countyFun (rule, value, callback) {
      if (!isEmpty(this.radiateScopeForm.startCountys) && this.radiateScopeForm.startCountys.length < 3) {
        return callback(new Error('请选择到区'));
      }
      callback();
    },
    notCountyFun (rule, value, callback) {
      if (!isEmpty(this.radiateScopeForm.endCountys) && this.radiateScopeForm.endCountys.length < 3) {
        return callback(new Error('请选择到区'));
      }
      callback();
    },
    createRadiateScopeClick () {
      if (isEmpty(this.radiateScopeForm.organizationId)) {
        return this.$message.error('请先选择组织');
      }

      this.$refs['radiateScopeForm'].validate((radiateScopeFormValid) => {
        if (radiateScopeFormValid) {
          //            this.radiateScopeForm.typeName = this.radiateScopeForm.type === '10001' ? '起点' : '终点';
          this.radiateScopeForm = this.setAddress(this.radiateScopeForm, data => {
            return data;
          });
          addOrganizationRadiateScopes(this.radiateScopeForm).then(res => {
            if (res.data.successFlg) {
              this.restForm();
              this.radiateScopeFormDialog = false;
              this.getOrganizationRadiateScopeList();
              this.$message.success('保存成功');
            }
          });
        }
      });
    },
    setAddress (o, fun) {
      if (!isEmpty(o.startProvinces)) {
        o.startProvinceName = getTreeIdAndNameToMap(o.startProvinces, this.radiateScopeProvince).get(o.startProvinces[0]);
        o.startProvince = o.startProvinces.join(',');
      }
      if (!isEmpty(o.startCitys)) {
        let cityModel = getTreeIdAndNameToMap(o.startCitys, this.radiateScopeCity);
        o.startCityName = cityModel.get(o.startCitys[0]) + ',' + cityModel.get(o.startCitys[1]);
        o.startCity = o.startCitys.join(',');
      }
      if (!isEmpty(o.startCountys)) {
        let countyModel = getTreeIdAndNameToMap(o.startCountys, this.radiateScopeCounty);
        o.startCountyName = countyModel.get(o.startCountys[0]) + ',' + countyModel.get(o.startCountys[1]) + ',' + countyModel.get(o.startCountys[2]);
        o.startCounty = o.startCountys.join(',');
      }
      if (!isEmpty(o.endProvinces)) {
        o.endProvinceName = getTreeIdAndNameToMap(o.endProvinces, this.radiateScopeProvince).get(o.endProvinces[0]);
        o.endProvince = o.endProvinces.join(',');
      }
      if (!isEmpty(o.endCitys)) {
        let notCityModel = getTreeIdAndNameToMap(o.endCitys, this.radiateScopeCity);
        o.endCityName = notCityModel.get(o.endCitys[0]) + ',' + notCityModel.get(o.endCitys[1]);
        o.endCity = o.endCitys.join(',');
      }
      if (!isEmpty(o.endCountys)) {
        let notCountyModel = getTreeIdAndNameToMap(o.endCountys, this.radiateScopeCounty);
        o.endCountyName = notCountyModel.get(o.endCountys[0]) + ',' + notCountyModel.get(o.endCountys[1]) + ',' + notCountyModel.get(o.endCountys[2]);
        o.endCounty = o.endCountys.join(',');
      }
      return fun(o);
    },
    restForm () {
      if (this.$refs.radiateScopeForm) {
        this.$refs.radiateScopeForm.resetFields();
      }
      for (let p in this.radiateScopeForm) {
        if (this.radiateScopeForm[p] instanceof Array) {
          this.radiateScopeForm[p] = [];
        } else {
          this.radiateScopeForm[p] = null;
        }
      }
    },
    addRadiateScope () {
      if (isEmpty(this.selectedRow)) {
        return this.$message.error('请先选择组织');
      }
      this.restForm();
      this.radiateScopeForm.organizationId = this.selectedRow.id;
      this.radiateScopeForm.organizationName = this.selectedRow.name;
      this.radiateScopeFormDialog = true;
      this.getAddress('level=1');
      this.getAddress('level=1,2');
      this.getAddress('level=1,2,3');
    },
    modifyRadiateScope (row) {
      if (this.$refs.radiateScopeForm) {
        this.$refs.radiateScopeForm.resetFields();
      }
      for (let p in this.radiateScopeForm) {
        if (this.radiateScopeForm[p] instanceof Array) {
          this.radiateScopeForm[p] = [];
        } else {
          this.radiateScopeForm[p] = null;
        }
      }
      this.getAddress('level=1');
      this.getAddress('level=1,2');
      this.getAddress('level=1,2,3');
      this.radiateScopeFormDialog = true;
      this.radiateScopeForm = Object.assign({
        startProvinces: [],
        startProvince: '',
        startProvinceName: '',
        startCitys: [],
        startCity: '',
        startCityName: '',
        startCountys: [],
        startCounty: '',
        startCountyName: '',
        endProvinces: [],
        endProvince: '',
        endProvinceName: '',
        endCitys: [],
        endCity: '',
        endCityName: '',
        endCountys: [],
        endCounty: '',
        endCountyName: '',
        organizationId: '',
        organizationName: ''
        //          type: '',
        //          typeName: ''
      }, row);
      this.toArray(row.startProvince, data => {
        this.radiateScopeForm.startProvinces = data;
      });
      this.toArray(row.startCity, data => {
        this.radiateScopeForm.startCitys = data;
      });
      this.toArray(row.startCounty, data => {
        this.radiateScopeForm.startCountys = data;
      });
      this.toArray(row.endProvince, data => {
        this.radiateScopeForm.endProvinces = data;
      });
      this.toArray(row.endCity, data => {
        this.radiateScopeForm.endCitys = data;
      });
      this.toArray(row.endCounty, data => {
        this.radiateScopeForm.endCountys = data;
      });
    },
    toArray (data, fun) {
      if (isEmpty(data)) {
        fun([]);
      } else {
        fun(data.split(',').map(function (dt) {
          return +dt;
        }));
      }
    },
    getAddress (filters) {
      addressDicts(filters).then(res => {
        let address = res.data.detailModelList;
        if (filters === 'level=1') {
          this.radiateScopeProvince = address;
        }
        if (filters === 'level=1,2') {
          this.radiateScopeCity = address;
        }
        if (filters === 'level=1,2,3') {
          this.radiateScopeCounty = address;
        }
      }).catch(err => {
        console.error(err);
      });
    },
    getOrganizationRadiateScopeList (filters) {
      this.radiateScopeTableData = [];
      getOrganizationRadiateScopes({
        filters: isEmpty(filters) ? 'EQ_organizationId=' + this.selectedRow.id : filters + ';EQ_organizationId=' + this.selectedRow.id,
        sorts: '',
        size: this.pSize,
        page: this.cPage
      }).then(res => {
        if (res.data.successFlg) {
          this.radiateScopeTableData = res.data.detailModelList;
          this.cPage = res.data.currPage;
          this.tts = res.data.totalCount;
          this.pSize = res.data.pageSize;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    deleteRadiateScope (row) {
      this.$confirm('您确认要删除该条数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrganizationRadiateScopes(row.id).then(res => {
          if (res.data.successFlg) {
            this.getOrganizationRadiateScopeList();
            this.$message.success('删除成功');
          } else {
            this.$message.success(res.data.errorMsg);
          }
        });
      });
    },
    handleDefaultOrgainzaion (index, row) {
      this.$confirm('您确认将该用户的默认组织设成【' + this.selectedRow.name + '】', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setCurrentOrgid(row.id, this.selectedRow.id).then(res => {
          if (res.data.successFlg) {
            this.$message('设置成功');
            this.loadCurrentOrgUser();
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      });
    },
    addCurrentUserRoles () {
      addRoles(this.currentUserId, [].concat(this.currentUserCurrentOrgRoleIds, this.currentUserNoCurrentOrgRoleIds))
        .then(res => {
          if (res.data.successFlg) {
            this.$message('添加角色成功!');
            this.roleWinVisible = false;
            this.loadCurrentOrgUser();
          }
        });
    },
    addCurrentUserDataPermissions () {
      addDataPermissions(this.currentUserId, [].concat(this.currentUserCurrentOrgDataPermissionIds, this.currentUserNoCurrentOrgDataPermissionIds))
        .then(res => {
          if (res.data.successFlg) {
            this.$message('添加数据组成功!');
            this.dataPermissionWinVisible = false;
            this.loadCurrentOrgUser();
          }
        });
    },
    handleRole (index, row) {
      this.roleWinVisible = true;
      this.currentUserId = row.id;
      this.currentUserCurrentOrgRoleIds = row.roleIds.filter(item => { return this.currentOrgRoleIds.indexOf(item) > -1; });
      this.currentUserNoCurrentOrgRoleIds = row.roleIds.filter(item => { return this.currentOrgRoleIds.indexOf(item) === -1; });
    },
    handleDataPermission (index, row) {
      this.dataPermissionWinVisible = true;
      this.currentUserId = row.id;
      this.currentUserCurrentOrgDataPermissionIds = row.dataPermissionIds.filter(item => { return this.currentOrgDataPermissionIds.indexOf(item) > -1; });
      this.currentUserNoCurrentOrgDataPermissionIds = row.dataPermissionIds.filter(item => { return this.currentOrgDataPermissionIds.indexOf(item) === -1; });
    },
    haveNoCurrentOrgUserSelsChange (sels) {
      this.noCurrentOrgUserSels = sels;
    },
    addUser () {
      if (this.$refs.noCurrentOrgUserDataTable) {
        this.$refs.noCurrentOrgUserDataTable.clearSelection();
      }
      this.noCurrentOrgUserWinVisible = true;
    },
    loadCurrentOrgUser () {
      this.loadUsers('EQ_organizations.id=' + this.selectedRow.id, data => {
        this.currentOrgUserData = data;
      });
    },
    addCurrentOrgUser () {
      let ids = this.noCurrentOrgUserSels.map(item => item.id);
      let id = this.selectedRow.id;
      addUsers(id, ids).then(res => {
        if (res.data.successFlg) {
          this.loadCurrentOrgUser();
          this.noCurrentOrgUserWinVisible = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },
    removeCurrentOrgUser () {
      this.$confirm('您确认从该机构移除这些用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.currentOrgUserSels.map(item => item.id);
        let id = this.selectedRow.id;
        removeUsers(id, ids).then(res => {
          if (res.data.successFlg) {
            this.loadUsers('EQ_organizations.id=' + id, data => {
              this.currentOrgUserData = data;
            });
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      });
    },
    haveCurrentOrgUserSelsChange (sels) {
      this.currentOrgUserSels = sels;
    },
    handleDelete (index, id) {
      this.$confirm('您确认删除该机构及其下面的子机构', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrganization(id).then(res => {
          if (res.data.successFlg) {
            this.loadOrganizationTree();
            this.$store.commit('initOrganizations', true);
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      });
    },
    handleCurrentChange (val) {
      if (val) {
        this.selectedRow = val;
        this.$refs.dotRule.load(val.id);
        this.loadCurrentOrgUser();
        this.currentOrgRoles = val.roles;
        this.currentOrgRoleIds = val.roles.map(item => { return item.id; });
        this.currentOrgDataPermissions = val.dataPermissions;
        this.currentOrgDataPermissionIds = val.dataPermissions.map(item => { return item.id; });
        this.$refs.organizationResource.setCheckedKeys(val.id);
        this.getOrganizationRadiateScopeList();
      } else {
        this.$refs.organizationResource.setCheckedKeys([]);
      }
    },
    handleEdit (index, row) {
      this.resetField();
      this.pids = row.pids;
      this.dialogTitle = '修改';
      this.myForm.id = row.id;
      this.myForm.name = row.name;
      this.myForm.alias = row.alias;
      this.myForm.type = row.type;
      this.myForm.sort = row.sort;
      this.myForm.attribute = row.attribute;
      this.myForm.divideRatio = row.divideRatio;
      this.myForm.deduction = row.deduction;
      this.myForm.jurisdictions = row.jurisdictions.map(o => {
        return {ids: o.countyIds.split(',').map(i => parseInt(i))};
      });
      this.myFormVisible = true;
    },
    handleAdd () {
      this.resetField();
      this.dialogTitle = '添加';
      this.myFormVisible = true;
      if (this.selectedRow) {
        this.pids = Object.assign([], this.selectedRow.pids);
        this.pids.push(this.selectedRow.id);
      }
    },
    handleSubmit () {
      if (this.myForm.id && this.myForm.parent.id && this.myForm.id === this.myForm.parent.id) {
        this.$message.warning('父机构不能是自己');
        return;
      }
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          if (this.myForm.attribute === 110007002) {
            this.myForm.jurisdictions.forEach(o => {
              o.countyId = o.ids[2];
              o.countyIds = o.ids.join(',');
            });
          } else {
            this.myForm.jurisdictions = [];
          }
          if (this.myForm.attribute !== 110007003) {
            this.myForm.deduction = false;
          }
          if (this.myForm.attribute !== 110007003 && this.myForm.attribute !== 110007002) {
            this.myForm.divideRatio = null;
            this.myForm.truckLoadDivideRatio = null;
          }
          saveOrganization(this.myForm).then(res => {
            if (res.data.successFlg) {
              this.myFormVisible = false;
              this.loadOrganizationTree();
              this.$store.commit('initOrganizations', true);
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
        }
      });
    },
    resetField () {
      if (this.$refs['myForm']) {
        this.$refs['myForm'].resetFields();
        this.myForm.id = null;
        this.myForm.name = null;
        this.myForm.sort = null;
        this.myForm.type = null;
        this.myForm.attribute = null;
        this.myForm.divideRatio = null;
        this.myForm.truckLoadDivideRatio = null;
        this.myForm.deduction = null;
        this.myForm.jurisdictions = [];
        this.pids = [];
      }
    },
    loadOrganizationTree () {
      this.listLoading = true;
      organizationTree().then(res => {
        this.listLoading = false;
        if (res.data.successFlg) {
          this.organizationTree = res.data.detailModelList;
        }
      });
    },
    loadUsers (filters, fun) {
      searchAllUsers({
        filters: filters
      }).then(res => {
        if (res.data.successFlg) {
          fun(res.data.detailModelList);
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    },

    // 每页几条操作
    hChange (val) {
      this.pSize = val;
      this.getOrganizationRadiateScopeList();
    },
    // 第几页操作
    hCChange (val) {
      this.cPage = val;
      this.getOrganizationRadiateScopeList();
    }
  },
  mounted () {
    this.loadOrganizationTree();
    this.$store.commit('initAddressDicts');
    this.$store.commit('initDict');
    this.loadUsers('', data => {
      this.noCurrentOrgUserData = data;
    });
  }
};
</script>
